package com.movitech.mobile.ddzy.modules.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movitech.mobile.cz.base.common.bpm.BpmUtil;
import com.movitech.mobile.cz.base.common.bpm.FlowFormDataVo;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.modules.config.AbutmentSubTypeEnum;
import com.movitech.mobile.cz.base.modules.config.AbutmentTypeEnum;
import com.movitech.mobile.cz.base.modules.config.CallBackAbutmentTypeEnum;
import com.movitech.mobile.cz.base.modules.config.PurchasePlanFlowTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.bizservice.WorkFlowService;
import com.movitech.mobile.cz.base.purchase.bizvo.*;
import com.movitech.mobile.cz.base.purchase.entity.PSpecialPurchasePlan;
import com.movitech.mobile.cz.base.purchase.entity.WFlowFormPurchaseTeam;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWFlowFormBackBid;
import com.movitech.mobile.cz.base.purchase.service.PSpecialPurchasePlanService;
import com.movitech.mobile.cz.base.purchase.service.SAbutmentLogsService;
import com.movitech.mobile.cz.base.sessionuser.SessionUserVo;
import com.movitech.mobile.cz.base.supplier.bizvo.HistoryCommentVO;
import com.movitech.mobile.cz.base.supplier.bizvo.SuppliersDetailVO;
import com.movitech.mobile.cz.base.supplier.bizvo.SuppliersLastThreeCommonAchievenVO;
import com.movitech.mobile.cz.base.supplier.bizvo.SuppliersLastThreeMajorAchievenVO;
import com.movitech.mobile.cz.base.supplier.entity.SSupplierRcRelate;
import com.movitech.mobile.cz.base.supplier.service.SSupplierRcRelateService;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.cz.base.sys.entity.SProject;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.entity.SysDict;
import com.movitech.mobile.cz.base.sys.service.SProjectService;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.sys.service.SysDictService;
import com.movitech.mobile.cz.base.util.UserUtils;
import com.movitech.mobile.ddzy.bpm.entity.SBpm;
import com.movitech.mobile.ddzy.bpm.entity.SBpmCallback;
import com.movitech.mobile.ddzy.bpm.feignclient.MbsDataAuthClient;
import com.movitech.mobile.ddzy.bpm.service.SBpmService;
import com.movitech.mobile.ddzy.bpm.vo.BpmFlowReturn;
import com.movitech.mobile.ddzy.bpm.vo.Users;
import com.movitech.mobile.ddzy.bpm.vo.cgr.CgrFlowForm;
import com.movitech.mobile.ddzy.bpm.vo.cgr.CgrFlowFormItem;
import com.movitech.mobile.ddzy.bpm.vo.cgr.CgrFlowReturn;
import com.movitech.mobile.ddzy.modules.bpm.bizservice.MbsBpmCallBackService;
import hk.modernland.utils.http.HttpClientUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

@Service(value = "cgrBpmUtil")
@RefreshScope
public class ExtCgrBpmUtil extends BpmUtil implements InitializingBean {

    private static Logger logger = Logger.getLogger(ExtCgrBpmUtil.class);

    @Autowired
    private PSpecialPurchasePlanService pSpecialPurchasePlanService;
    @Autowired
    @Qualifier("mbsBpmCallBackService")
    private MbsBpmCallBackService mbsBpmCallBackService;
    @Autowired
    private SysDictService sysDictService;

    @Autowired
    @Qualifier("sAbutmentLogsService")
    private SAbutmentLogsService sAbutmentLogsService;
    @Autowired
    private SSuppliersService sSuppliersService;
    @Autowired
    private SProjectService sProjectService;

    @Autowired
    private SSupplierRcRelateService sSupplierRcRelateService;
    @Autowired
    private SRegionalCompanyService sRegionalCompanyService;
    @Autowired
    @Qualifier("sBpmService")
    private SBpmService sBpmService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private MbsDataAuthClient mbsDataAuthClient;

    // 金源流程创建流程
    // http://por.test.cgr.com.cn:8010/portal/Webservices/BPMTest2Service.asmx/StartWorkflowNew
    @Value("${cgr.bpm.url}")
    private String cgrBpmUrl;
    // http://por.test.cgr.com.cn:8010/portal/Webservices/BPMTest2Service.asmx/StartWorkflowNew

    // 金源流程审批页面地址；
    @Value("${cgr.bpm.detail.url}")
    private String cgrBpmDetailUrl;

    // 审批页面跳转详情时，单点中转URL
    // http://sso.grtyzk.com.cn/sso/join/ssoUrlPass?u=admin&service=
    @Value("${cgr.bpm.turn_url}")
    private String cgrBpmTurnUrl;

    //是否打开审批流程
    @Value("${cgr.bpm.enable}")
    private String enableBpm;
    @Value("${cgr.bpm.purchase.enable}")
    private String enablePurchaseBpm;

    @Value("${cgr.bpm.testusercode}")
    private String testUsercode;

    // 腾去筑科平台供方入库审批流程模板编码
    @Value("${cgr.bpm.supplier.storage.workflowcode}")
    private String supplierStorageWorkflowCode;
    // 其他小平台供方入库审批流程模板编码
    @Value("${cgr.bpm.supplier.storage.otherPlateWorkflowCode}")
    private String supplierStorageOtherPlateWorkflowCode;
    // 定标流程审批流程模板编码
    @Value("${cgr.bpm.calibractionbid.workflowcode}")
    private String calibrationBidWorkflowCode;
    @Value("${cgr.bpm.calibractionbid.supplier_url}")
    private String awardbidSupplierUrl;
    // 采购系统定标详情页面地址
    @Value("${cgr.bpm.calibractionbid.page_url}")
    private String calibrationBidPageUrl;

    // 采购方案审批流程模板编码
    @Value("${cgr.bpm.purchasesolution.workflowcode}")
    private String purchaseSolutionDocWorkflowCode;
    // 采购系统定标详情页面地址
    @Value("${cgr.bpm.purchasesolution.page_url}")
    private String purchaseSolutionPageUrl;

    // 招标文件审批流程模板编码
    @Value("${cgr.bpm.biddoc.workflowcode}")
    private String biddocWorkflowCode;
    // 招标文件详情页面地址
    @Value("${cgr.bpm.biddoc.page_url}")
    private String biddocPageUrl;

    // 腾云筑科平台名称
    @Value("${cgr.bpm.supplier.storage.zukePlateName}")
    private String zukePlateName;


    @Value("${cgr.bpm.supplier.storage.page_url}")
    private String mbsSupplierStorageTagUrl;

    public void setEnableBpm(String enableBpm) {
        System.out.println("是否开始流程审批：" + enableBpm);
        this.enableBpm = enableBpm;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("是否开始流程审批：" + this.enableBpm);
        System.out.println("是否开始流程审批：" + "Y".equals(this.enableBpm));
    }

    public Users getCurrentUser() {
        LicenseUtil.INSTANCE.validate();
        SessionUserVo userVo = UserUtils.getCurrentUserVo();
        Users users = new Users();
        users.setEmployeeID(userVo.getEmployeeID());
        String userJson = mbsDataAuthClient.getUser(users);
        JSONObject jsonObject = JSON.parseObject(userJson);
        JSONObject user = JSON.parseObject(jsonObject.getString("data"));
        Users currentUser = user.toJavaObject(Users.class);
        return currentUser;
    }

    public CgrBpmTemplateUtil.FlowTemplate getFlowTemplate(CgrBpmTemplateUtil.FlowKindEnum flowKind, String projectId) {
        SProject project = sProjectService.selectById(projectId);
        return CgrBpmTemplateUtil.getFlowTemplate(flowKind, project.getProjectCode());
    }

    /***
     * 调用供方入库审批流程
     * @param mapParams
     * @param actionType
     * @return
     * @throws RuntimeException
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public Map<String, Object> invokeApprovalFlow(Map<String, Object> mapParams, int actionType) throws RuntimeException {
        System.out.println("===========BpmUtil-->invokeApprovalFlow");

        LicenseUtil.INSTANCE.validate();
        boolean isSuccess = true;
        String currentUserId = "";
        String relatedId = "";
        String subRelatedId = "";
        String orgCode = "";
        String orgName = "";
        String employeeCode = "";


        Map<String, Object> mapBpmParams = new HashMap<String, Object>();
        try {
            if (mapParams != null) {
                currentUserId = StringUtils.object2StringNotNull(mapParams.get("CURRENT_USER_ID"));
                relatedId = StringUtils.object2StringNotNull(mapParams.get("RELATE_ID"));
                subRelatedId = StringUtils.object2StringNotNull(mapParams.get("SUB_RELATE_ID"));
                orgCode = StringUtils.object2StringNotNull(mapParams.get("ORG_CODE"));
                orgName = StringUtils.object2StringNotNull(mapParams.get("ORG_NAME"));
                employeeCode = StringUtils.object2StringNotNull(mapParams.get("EMPLOYEE_CODE"));
                if (actionType == AbutmentSubTypeEnum.RANK_APPROVE.getCode()) {//供应商定级审批
                    ///写对接时的请求数据获取代码
                    mapBpmParams.put("formId", IdGenUtils.randomInt());
                    mapBpmParams.put("comCode", orgCode);
                    mapBpmParams.put("comName", orgName);
                    mapBpmParams.put("employeeId", employeeCode);
                    ///对接BPM
                    mapBpmParams = doAuto(currentUserId, CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER, actionType, relatedId, subRelatedId, "SupplierRankFlow", mapBpmParams);
                } else {

                    mapBpmParams.put("userName", StringUtils.object2StringNotNull(mapParams.get("CURRENT_USER_NAME")));
                    mapBpmParams.put("formId", IdGenUtils.randomInt());
                    mapBpmParams.put("comCode", orgCode);
                    mapBpmParams.put("comName", orgName);
                    mapBpmParams.put("employeeId", employeeCode);
                    CgrFlowForm flowForm = null;
                    if (actionType == AbutmentSubTypeEnum.STORE_APPROVE.getCode()) {

                        mapBpmParams.put("flowKind", mapParams.get("flowKind"));

                        // 写对接时的请求数据获取代码
                        mapBpmParams.put("tagUrl", mbsSupplierStorageTagUrl + subRelatedId + "?mbs=1");
                        // 详情地址
                        flowForm = createStorageData(mapBpmParams, subRelatedId);
                        ///对接BPM
                        System.out.println("是否开始流程审批：" + this.enableBpm);
                        System.out.println("是否开始流程审批：" + "Y".equals(this.enableBpm));
                        mapBpmParams = doAbutmentBpm(currentUserId, CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER, actionType, relatedId, subRelatedId, "SupplierStorageFlow", mapBpmParams, flowForm);
                    } else if (actionType == AbutmentSubTypeEnum.TURN_TO_PENDING_WATCH_APPROVE.getCode()) {
                        // 转待观察审批
                        mapBpmParams = doAuto(currentUserId, CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER, actionType, relatedId, subRelatedId, "SupplierTurnToWatchFlow", mapBpmParams);
                    } else if (actionType == AbutmentSubTypeEnum.TURN_TO_UNQUALIFIED_APPROVE.getCode()) {
                        ///转不合格审批
                        mapBpmParams = doAuto(currentUserId, CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER, actionType, relatedId, subRelatedId, "SupplierTurnUnqualifiedFlow", mapBpmParams);
                    } else if (actionType == AbutmentSubTypeEnum.TURN_TO_POTENTIAL_APPROVE.getCode()) {
                        // 转潜在审批
                        mapBpmParams = doAuto(currentUserId, CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER, actionType, relatedId, subRelatedId, "SupplierTurnPotentialFlow", mapBpmParams);
                    } else if (actionType == AbutmentSubTypeEnum.TURN_TO_BLACK_LIBRARY_APPROVE.getCode()) {
                        //转黑库审批
                        mapBpmParams = doAuto(currentUserId, CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER, actionType, relatedId, subRelatedId, "SupplierTurnBlackLibraryFlow", mapBpmParams);
                    }
                }
            }
        } catch (
                Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return mapBpmParams;
    }

    /***
     * 对接BPM
     * @param mapBpmParams
     * @throws Exception
     */
    private Map<String, Object> doAbutmentBpm(String currentUserId, Integer abutmentType, Integer abutmentSubType, String relatedId, String subRelatedId, String bpmRelatedType, Map<String, Object> mapBpmParams, CgrFlowForm flowForm) throws Exception {
        boolean isSuccess = false;
        BpmFlowReturn bpmFlowReturn = new BpmFlowReturn();
        String mbsUrl = null;
        Map<String, Object> mapResult = new HashMap<String, Object>();
        SSupplierRcRelate rcRelate = null;
        SRegionalCompany regionalCompany = null;
        RestReturnResult<SuppliersDetailVO> supplierVo = null;
        if (mapBpmParams.get("rcRelate") != null) {
            rcRelate = (SSupplierRcRelate) mapBpmParams.get("rcRelate");
        } else {
            rcRelate = sSupplierRcRelateService.getSupplierRcRelateById(subRelatedId);
        }
        if (mapBpmParams.get("regionalCompany") != null) {
            regionalCompany = (SRegionalCompany) mapBpmParams.get("regionalCompany");
        } else {
            regionalCompany = sRegionalCompanyService.selectById(rcRelate.getRegionalCompanyId());
        }
        /*if (mapBpmParams.get("supplierVo") != null) {
            supplierVo = (RestReturnResult<SuppliersDetailVO>) mapBpmParams.get("supplierVo");
        }else{
            supplierVo = sSuppliersService.getByRelatedId(subRelatedId);
        }*/
        Gson gson = new Gson();
        String workflowId = "";
        Map<String, String> params = new HashMap<>();
        params.put("userCode", StringUtils.object2StringNotNull(mapBpmParams.get("userName")));
        if ("test".equals(this.enableBpm)) {
            params.put("userCode", this.testUsercode);
        }
        LicenseUtil.INSTANCE.validate();
        params.put("finishStart", "true");
        params.put("subTableName", "");
        params.put("RejectInstanceid", StringUtils.object2StringNotNull(workflowId));
        params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
        if (flowForm != null && flowForm.getFlowForm().size() > 0) {
            // 入库审批
            // 首先判断流程是否是被打回后，再次提交的，获取流程ID.
            if (abutmentSubType == AbutmentSubTypeEnum.STORE_APPROVE.getCode()) {
                /*if (zukePlateName.equals(regionalCompany.getRegionalCompanyName())) {
                    // 腾云筑科平台入库审批流程。
                    params.put("workflowCode", this.supplierStorageWorkflowCode);
                    params.put("subTableName", "YBHZQK;ZLHZQK");//子表
                } else {
                    // 其他小平台入库审批流程
                    params.put("workflowCode", this.supplierStorageOtherPlateWorkflowCode);
                    params.put("subTableName", "YBHZQKXM;ZLHZQKXM");//子表
                }*/
                params.put("workflowCode", flowForm.getFlowCode());
                params.put("subTableName", "YBHZQKXM;ZLHZQKXM");//子表

                Map<String, Object> q = new HashMap<>();
                q.put("subRelatedId", subRelatedId);
                q.put("bpmRelatedType", bpmRelatedType);
                workflowId = sBpmService.getBpmWorkflowId(q);

            } else if (abutmentSubType == AbutmentSubTypeEnum.TURN_TO_PENDING_WATCH_APPROVE.getCode()) {
                // 转待观察审批
            } else if (abutmentSubType == AbutmentSubTypeEnum.TURN_TO_UNQUALIFIED_APPROVE.getCode()) {
                ///转不合格审批
            } else if (abutmentSubType == AbutmentSubTypeEnum.TURN_TO_POTENTIAL_APPROVE.getCode()) {
                // 转潜在审批
            } else if (abutmentSubType == AbutmentSubTypeEnum.TURN_TO_BLACK_LIBRARY_APPROVE.getCode()) {
                //转黑库审批
            }
            params.put("RejectInstanceid", StringUtils.object2StringNotNull(workflowId));
            String paramJson = JSON.toJSONString(params);
            System.out.println("============doAbutmentBpm=======[request]=========" + paramJson);
            sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_11.getCode(), relatedId, paramJson, 0, 0);
            String flowReturnJson = "";
            if ("Y".equals(this.enableBpm)) {
                flowReturnJson = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
            } else if ("test".equals(this.enableBpm)) {
                flowReturnJson = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
            } else {
                workflowId = IdGenUtils.uuid();
                flowReturnJson = "{\"Success\":true,\"ErrorMessage\":\"\",\"Data\":\"" + workflowId + "\",\"Sequenceno\":\"ZK_AUTO_0022023000017\"}";
            }
            System.out.println("============doAbutmentBpm=======[result]=========" + flowReturnJson);
            if (StringUtils.isNotEmpty(flowReturnJson)) {
                String content = flowReturnJson.substring(flowReturnJson.indexOf("{"), flowReturnJson.indexOf("}") + 1);
                CgrFlowReturn cgrFlowReturn = gson.fromJson(content, new TypeToken<CgrFlowReturn>() {
                }.getType());
                if (cgrFlowReturn != null) {
                    if ("true".equals(cgrFlowReturn.getSuccess())) {
                        bpmFlowReturn.setWorkFlowId(cgrFlowReturn.getData());
                        workflowId = cgrFlowReturn.getData();
                        bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                        bpmFlowReturn.setUrl("");
                        bpmFlowReturn.setFormId("1");
                        saveSBpm(currentUserId, abutmentType, abutmentSubType, relatedId, subRelatedId, bpmRelatedType, bpmFlowReturn, flowReturnJson, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                        isSuccess = true;
                    } else {
                        saveSBpm(currentUserId, abutmentType, abutmentSubType, relatedId, subRelatedId, bpmRelatedType, bpmFlowReturn, flowReturnJson, JSON.toJSONString(params), CommonConstants.NO_INTEGER);
                    }
                }
            } else {
                if ("Y".equals(this.enableBpm) || "test".equals(this.enableBpm)) {
                    throw new RuntimeException("流程发起失败！！!");
                }
            }
        }


        //直接审批回调
        if ("autoPass".equals(this.enableBpm)) {
            Map<String, String> callParams = new HashMap<>();
            callParams.put("evenType", "1");
            callParams.put("BPMId", workflowId);
            this.bpmCallback(callParams);
        } else if ("autoUnPass".equals(this.enableBpm)) {
            Map<String, String> callParams = new HashMap<>();
            callParams.put("evenType", "2");
            callParams.put("BPMId", workflowId);
            this.bpmCallback(callParams);
        } else {
//            throw new RuntimeException("TEST");
        }

        mapResult.put("IS_SUCCESS", isSuccess);
        // 金源BPM不支持业务系统直接打开审批页面查询详情
        mapResult.put("MBS_URL", cgrBpmDetailUrl + workflowId);
        return mapResult;
    }

    /***
     * 不对接对接BPM，直接审批通过
     * @param mapBpmParams
     * @throws Exception
     */
    private Map<String, Object> doAuto(String currentUserId, Integer abutmentType, Integer abutmentSubType, String relatedId, String subRelatedId, String bpmRelatedType, Map<String, Object> mapBpmParams) throws Exception {

        String paramJson = JSON.toJSONString(mapBpmParams);
        sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_11.getCode(), relatedId, paramJson, 0, 0);

        LicenseUtil.INSTANCE.validate();
        String workFlowId = IdGenUtils.uuid();
        BpmFlowReturn bpmFlowReturn = new BpmFlowReturn();
        bpmFlowReturn.setState("1");
        bpmFlowReturn.setFormId("");
        bpmFlowReturn.setWorkFlowId(workFlowId);
        bpmFlowReturn.setUrl("");
        saveSBpm(currentUserId, abutmentType, abutmentSubType, relatedId, subRelatedId, bpmRelatedType, bpmFlowReturn, "自动审批", paramJson, CommonConstants.YES_INTEGER);
        //直接审批回调
        Map<String, String> callParams = new HashMap<>();
        callParams.put("evenType", "1");
        callParams.put("BPMId", workFlowId);
        this.bpmCallback(callParams);

        Map<String, Object> mapResult = new HashMap<String, Object>();
        mapResult.put("IS_SUCCESS", true);
        mapResult.put("MBS_URL", "javascript:void(0)");
        return mapResult;
    }

    /**
     * 生成供方入库审批表单数据
     *
     * @param mapParams
     * @param subRelatedId
     */
    public CgrFlowForm createStorageData(Map<String, Object> mapParams, String subRelatedId) throws UnsupportedEncodingException {
        LicenseUtil.INSTANCE.validate();

        String projectKind = String.valueOf(mapParams.get("flowKind"));

        if (StringUtils.isEmpty(projectKind)) {
            throw new RuntimeException("请选择入库审批流程类型");
        }

        CgrBpmTemplateUtil.FlowTemplate flowTemplate = CgrBpmTemplateUtil.getStorageApprovalFlowTemplate(projectKind);

        SSupplierRcRelate rcRelate = sSupplierRcRelateService.getSupplierRcRelateById(subRelatedId);
        SRegionalCompany regionalCompany = sRegionalCompanyService.selectById(rcRelate.getRegionalCompanyId());
        RestReturnResult<SuppliersDetailVO> supplierVo = sSuppliersService.getByRelatedId(subRelatedId);
        SuppliersDetailVO suppliersDetailVO = supplierVo.getData();
        System.out.println("rcRelate：" + JSONObject.toJSONString(rcRelate));
        System.out.println("regionalCompany：" + JSONObject.toJSONString(regionalCompany));
        System.out.println("supplierVo：" + JSONObject.toJSONString(supplierVo));
        mapParams.put("rcRelate", rcRelate);
        mapParams.put("regionalCompany", regionalCompany);
        mapParams.put("supplierVo", supplierVo);
        CgrFlowForm flowForm = new CgrFlowForm();
        flowForm.setFlowCode(flowTemplate.code);
        // 供方名称
        flowForm.addItem("SUPPLIER_NAME", suppliersDetailVO.getSuppliersVO().getCompanyName());
        // 所属平台名称
        flowForm.addItem("title", suppliersDetailVO.getSuppliersVO().getCompanyName() + "入库请示");
        // 从权限系统获取当前人员所属部门
        // 操作人员所属部门
        Users us = getCurrentUser();
        flowForm.addItem("ShenBanBuMen", us.getDeptuuid());
        //  事项类型
        flowForm.addItem("ShiXiangLeiXing", "");
        //  情况说明
        flowForm.addItem("QingKuangShuoMing", "");
        //  附件
        flowForm.addItem("FuJian", "");
        //  审批意见
        List<HistoryCommentVO> comment = suppliersDetailVO.getLstHistoryCommentVO();
        if (comment != null && comment.size() > 0) {
//            flowForm.addItem("ShenPiYiJian", comment.get(0).getCommentContent());
        } else {
//            flowForm.addItem("ShenPiYiJian", "");
        }
        flowForm.addItem("ShenPiYiJian", "");
        //
        flowForm.addItem("OUCompany", "");
        // 所在区域
        flowForm.addItem("SuoZaiQuyu", suppliersDetailVO.getSuppliersVO().getHeadquartersAddress());
        // 供方服务类别
        flowForm.addItem("GFFWLB", suppliersDetailVO.getSuppliersVO().getSupplierServiceCategoryNames());
        // 供方类型
        flowForm.addItem("GFLX", suppliersDetailVO.getSuppliersVO().getSupplierCategoryNames());
        // 意向平台公司
        flowForm.addItem("YXPTGS", regionalCompany.getRegionalCompanyName());
        flowForm.addItem("YXPTGS1", regionalCompany.getRegionalCompanyName());
        // 可承接省份
        flowForm.addItem("KCJSF", suppliersDetailVO.getSuppliersVO().getUndertakeAreasNames());
        // 资质等级
        flowForm.addItem("ZZDJ", "-");
        // 上年营业额（万元）
        flowForm.addItem("SNYYE", String.valueOf(suppliersDetailVO.getSuppliersBusinessSituationVO().getLastYearSales()));
        //供应商来源
        flowForm.addItem("GYSLY", suppliersDetailVO.getSuppliersVO().getSupplierSourceInfo());
        String detailUrl = mbsSupplierStorageTagUrl + subRelatedId + "?mbs=1";
        flowForm.addItem("SUPPLIER_URL", cgrBpmTurnUrl + URLEncoder.encode(detailUrl, "UTF-8"));
        //详情地址
        flowForm.addItem("XXXXLJ1", cgrBpmTurnUrl + URLEncoder.encode(detailUrl, "UTF-8"));

        // 战略合作情况 子表
        if (true) {
            CgrFlowFormItem zlhzqk = flowForm.addItem("ZLHZQK", "");
            List<Object> zlhzqk_ZBItemParamList = new ArrayList<>();
            List<SuppliersLastThreeMajorAchievenVO> lst = suppliersDetailVO.getLstSuppliersLastThreeMajorAchievenVO();
            if (lst != null && lst.size() > 0) {
                for (int i = 0; i < lst.size(); i++) {
                    SuppliersLastThreeMajorAchievenVO item = lst.get(i);
                    List<CgrFlowFormItem> list = new ArrayList<>();
                    if (StringUtils.isEmpty(item.getCooperativeUnitName())) {
                        continue;
                    }
                    list.add(CgrFlowForm.createItem("HZDW", item.getCooperativeUnitName()));
                    list.add(CgrFlowForm.createItem("HZLB", item.getCooperativeCategoryName()));
                    if (item.getCooperativeStartTime() != null) {
                        list.add(CgrFlowForm.createItem("HZKSSJ", DateUtils.formatDate(item.getCooperativeStartTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZKSSJ", ""));
                    }
                    if (item.getCooperativeEndTime() != null) {

                        list.add(CgrFlowForm.createItem("HZJSSJ", DateUtils.formatDate(item.getCooperativeEndTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZJSSJ", ""));
                    }
                    list.add(CgrFlowForm.createItem("SHJX", item.getAwards()));
                    list.add(CgrFlowForm.createItem("HZQY", item.getCooperativeAreaName()));
                    if (item.getCooperationAmount() != null) {
                        list.add(CgrFlowForm.createItem("HTJE", String.valueOf(item.getCooperationAmount().intValue())));
                    } else {
                        list.add(CgrFlowForm.createItem("HTJE", "0"));
                    }
                    zlhzqk_ZBItemParamList.add(list);
                }

            }
            zlhzqk.setZBItemParamList(zlhzqk_ZBItemParamList);

            //小平台
            CgrFlowFormItem zlhzqkxm = flowForm.addItem("ZLHZQKXM", "");
            List<Object> zlhzqkxm_ZBItemParamList = new ArrayList<>();
            if (lst != null && lst.size() > 0) {
                for (int i = 0; i < lst.size(); i++) {
                    SuppliersLastThreeMajorAchievenVO item = lst.get(i);
                    List<CgrFlowFormItem> list = new ArrayList<>();
                    if (StringUtils.isEmpty(item.getCooperativeUnitName())) {
                        continue;
                    }
                    list.add(CgrFlowForm.createItem("HZDW", item.getCooperativeUnitName()));
                    list.add(CgrFlowForm.createItem("HZLB", item.getCooperativeCategoryName()));
                    if (item.getCooperativeStartTime() != null) {
                        list.add(CgrFlowForm.createItem("HZKSSJ", DateUtils.formatDate(item.getCooperativeStartTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZKSSJ", ""));
                    }
                    if (item.getCooperativeEndTime() != null) {

                        list.add(CgrFlowForm.createItem("HZJSSJ", DateUtils.formatDate(item.getCooperativeEndTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZJSSJ", ""));
                    }
                    list.add(CgrFlowForm.createItem("SHJX", item.getAwards()));
                    list.add(CgrFlowForm.createItem("HZQY", item.getCooperativeAreaName()));
                    if (item.getCooperationAmount() != null) {
                        list.add(CgrFlowForm.createItem("HTJE", String.valueOf(item.getCooperationAmount().intValue())));
                    } else {
                        list.add(CgrFlowForm.createItem("HTJE", "0"));
                    }
                    zlhzqkxm_ZBItemParamList.add(list);
                }

            }
            zlhzqkxm.setZBItemParamList(zlhzqkxm_ZBItemParamList);
        }

        if (true) {
            // 一般合作情况 子表
            List<SuppliersLastThreeCommonAchievenVO> lst = suppliersDetailVO.getLstSuppliersLastThreeCommonAchievenVO();
            CgrFlowFormItem ybhzqk = flowForm.addItem("YBHZQK", "");
            List<Object> ybhzqk_ZBItemParamList = new ArrayList<>();
            if (lst != null && lst.size() > 0) {
                for (int i = 0; i < lst.size(); i++) {
                    List<CgrFlowFormItem> list = new ArrayList<>();
                    SuppliersLastThreeCommonAchievenVO item = lst.get(i);
                    if (StringUtils.isEmpty(item.getCooperativeUnitName())) {
                        continue;
                    }
                    list.add(CgrFlowForm.createItem("HZDW", item.getCooperativeUnitName()));
                    list.add(CgrFlowForm.createItem("HZXM", item.getCooperativeProjectName()));
                    if (item.getCooperativeStartTime() != null) {
                        list.add(CgrFlowForm.createItem("HZKSSJ", DateUtils.formatDate(item.getCooperativeStartTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZKSSJ", ""));
                    }
                    if (item.getCooperativeEndTime() != null) {
                        list.add(CgrFlowForm.createItem("HZJSSJ", DateUtils.formatDate(item.getCooperativeEndTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZJSSJ", ""));
                    }
                    list.add(CgrFlowForm.createItem("XMGM", item.getCooperativeProjectScale()));
                    list.add(CgrFlowForm.createItem("HZFW", item.getCooperationScope()));
                    if (item.getCooperationAmount() != null) {
                        list.add(CgrFlowForm.createItem("HTJE", String.valueOf(item.getCooperationAmount().intValue())));
                    } else {
                        list.add(CgrFlowForm.createItem("HTJE", "0"));
                    }
                    ybhzqk_ZBItemParamList.add(list);
                }
            }
            ybhzqk.setZBItemParamList(ybhzqk_ZBItemParamList);

            CgrFlowFormItem ybhzqkxm = flowForm.addItem("YBHZQKXM", "");
            List<Object> ybhzqkxm_ZBItemParamList = new ArrayList<>();
            if (lst != null && lst.size() > 0) {
                for (int i = 0; i < lst.size(); i++) {
                    List<CgrFlowFormItem> list = new ArrayList<>();
                    SuppliersLastThreeCommonAchievenVO item = lst.get(i);
                    if (StringUtils.isEmpty(item.getCooperativeUnitName())) {
                        continue;
                    }
                    list.add(CgrFlowForm.createItem("HZDW", item.getCooperativeUnitName()));
                    list.add(CgrFlowForm.createItem("HZXM", item.getCooperativeProjectName()));
                    if (item.getCooperativeStartTime() != null) {
                        list.add(CgrFlowForm.createItem("HZKSSJ", DateUtils.formatDate(item.getCooperativeStartTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZKSSJ", ""));
                    }
                    if (item.getCooperativeEndTime() != null) {
                        list.add(CgrFlowForm.createItem("HZJSSJ", DateUtils.formatDate(item.getCooperativeEndTime())));
                    } else {
                        list.add(CgrFlowForm.createItem("HZJSSJ", ""));
                    }
                    list.add(CgrFlowForm.createItem("XMGM", item.getCooperativeProjectScale()));
                    list.add(CgrFlowForm.createItem("HZFW", item.getCooperationScope()));
                    if (item.getCooperationAmount() != null) {
                        list.add(CgrFlowForm.createItem("HTJE", String.valueOf(item.getCooperationAmount().intValue())));
                    } else {
                        list.add(CgrFlowForm.createItem("HTJE", "0"));
                    }
                    ybhzqkxm_ZBItemParamList.add(list);
                }
            }
            ybhzqkxm.setZBItemParamList(ybhzqkxm_ZBItemParamList);
        }

        return flowForm;
        /*Map<String, String> params = new HashMap<>();
        params.put("userCode", StringUtils.object2StringNotNull(mapParams.get("userName")));
        params.put("userCode", "zukecs1");
        // 供方入库流程模板
        params.put("workflowCode", supplierStorageWorkflowCode);
//        params.put("workflowCode", "GongFangChuRuKu");
        params.put("finishStart", "true");
        params.put("subTableName", "YBHZQK;ZLHZQK");
        // 流程实例ID，查询是否存在被打回流程，若有被打回的，则使用原流程实例ID;
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("subRelatedId", ""); //供方子ID
        queryParams.put("bpmRelatedType", ""); //流程类型
        String workflowId = sBpmService.getBpmWorkflowId(queryParams);
        params.put("RejectInstanceid", workflowId == null ? "" : workflowId);
        params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
        return params;*/

    }


    /***
     * 调用采购方案接口
     * @param flowFormDataVo
     * @return
     */
    @Override
    public Map<String, Object> invokePurchaseSolutionDoc(FlowFormDataVo flowFormDataVo) {
        LicenseUtil.INSTANCE.validate();
        try {
            System.out.println("===========BpmUtil-->invokePurchaseSolutionDoc");
            CgrFlowForm flowForm = createPurchaseSolutionDocFormData(flowFormDataVo);
            Gson gson = new Gson();
            Map<String, Object> mapData = new HashMap<String, Object>();
            mapData.put("data", flowFormDataVo); //数据
            //查询定标流程
            Map<String, Object> q = new HashMap<>();
            q.put("subRelatedId", flowFormDataVo.getScServiceUuid());
            q.put("bpmRelatedType", "PurchaseScheme");
            String workflowId = sBpmService.getBpmWorkflowId(q);

            Map<String, String> params = new HashMap<String, String>();
//            params.put("workflowCode", this.purchaseSolutionDocWorkflowCode);
            params.put("workflowCode", flowForm.getFlowCode());
            Users us = getCurrentUser();
            params.put("userCode", StringUtils.object2StringNotNull(us.getUsername()));
//            params.put("userCode", StringUtils.object2StringNotNull(flowFormDataVo.getScCreateUserName()));
            params.put("finishStart", "true");
            params.put("subTableName", "");
            params.put("RejectInstanceid", StringUtils.object2StringNotNull(workflowId));
            String returnResult = "";
            if ("Y".equals(this.enablePurchaseBpm)) {
                //生产环境
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                returnResult = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_5.getCode());
            } else if ("test".equals(this.enablePurchaseBpm)) {
                //金源测试环境
                params.put("userCode", this.testUsercode);
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                returnResult = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_5.getCode());
            } else {
                //开发环境
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_5.getCode());
            }

            String paramJson = JSON.toJSONString(params);
            logger.info("SynDataServiceImpl[invokeApprovalCalibrationBid],ParamJson[" + paramJson + "],Result[" + returnResult + "]");

            System.out.println("============invokeApprovalCalibrationBid=======[result]=========" + returnResult);

            String cgrWorkflowId = "";
            BpmFlowReturn bpmFlowReturn = new BpmFlowReturn();
            if (StringUtils.isNotEmpty(returnResult)) {
                String content = returnResult.substring(returnResult.indexOf("{"), returnResult.indexOf("}") + 1);
                if (StringUtils.isNotEmpty(content)) {
                    CgrFlowReturn cgrFlowReturn = gson.fromJson(content, new TypeToken<CgrFlowReturn>() {
                    }.getType());
                    if (cgrFlowReturn != null) {
                        if ("true".equals(cgrFlowReturn.getSuccess())) {
                            cgrWorkflowId = cgrFlowReturn.getData();
                            bpmFlowReturn.setWorkFlowId(cgrFlowReturn.getData());
                            bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                            bpmFlowReturn.setUrl("");
                            bpmFlowReturn.setFormId("1");
                            saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_PURCHASE_SCHEME.getCode(), flowFormDataVo.getScServiceUuid(), flowFormDataVo.getScServiceUuid(), "PurchaseScheme", bpmFlowReturn, returnResult, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                        } else {
                            saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_PURCHASE_SCHEME.getCode(), flowFormDataVo.getScServiceUuid(), flowFormDataVo.getScServiceUuid(), "PurchaseScheme", bpmFlowReturn, "", JSON.toJSONString(params), CommonConstants.NO_INTEGER);
                            throw new RuntimeException("流程发起失败！！!");
                        }
                    } else {
                        throw new RuntimeException("流程发起失败！！!");
                    }
                } else {
                    throw new RuntimeException("流程发起失败！！!");
                }
            } else {
                if ("Y".equals(this.enablePurchaseBpm) || "test".equals(this.enablePurchaseBpm)) {
                    throw new RuntimeException("流程发起失败！！!");
                }
                String workFlowId = IdGenUtils.uuid();
                bpmFlowReturn.setWorkFlowId(workFlowId);
                bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                bpmFlowReturn.setUrl("");
                bpmFlowReturn.setFormId("1");
                saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_PURCHASE_SCHEME.getCode(), flowFormDataVo.getScServiceUuid(), flowFormDataVo.getScServiceUuid(), "PurchaseScheme", bpmFlowReturn, returnResult, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                //直接审批回调
                if ("autoPass".equals(this.enablePurchaseBpm)) {
                    Map<String, String> callParams = new HashMap<>();
                    callParams.put("evenType", "1");
                    callParams.put("BPMId", workFlowId);
                    this.bpmCallback(callParams);
                } else if ("autoUnPass".equals(this.enablePurchaseBpm)) {
                    Map<String, String> callParams = new HashMap<>();
                    callParams.put("evenType", "2");
                    callParams.put("BPMId", workFlowId);
                    this.bpmCallback(callParams);
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("IS_SUCCESS", true);
            result.put("BPM_URL", this.cgrBpmDetailUrl + cgrWorkflowId);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("流程发起失败", e);
        }
    }

    /**
     * 生成采购方案 流程表单
     */
    private CgrFlowForm createPurchaseSolutionDocFormData(FlowFormDataVo flowFormDataVo) throws UnsupportedEncodingException {
        CgrFlowForm flowForm = new CgrFlowForm();
        String formId = flowFormDataVo.getScServiceUuid();
        //1、查询采购方案
        HeaderVO headerVO = workFlowService.selectHeaderList(formId);
        PurchasePlanNodeAllDataResVO vo = workFlowService.selectPurchasePlanNodeData(formId);
        SysDict dictContractValuationMethod = sysDictService.getSysDictByValueAndType(headerVO.getFlowForm().getContractValuationMethod() + "", DictTypeConstants.SYS_DICT_TYPE_CONTRACT_VALUATION_METHOD_TYPE_MAP);
        ConfirmBidNodeAllDataResVO datas = workFlowService.selectConfirmBidNodeData(formId);
        InquiringBidRspVO jspp = workFlowService.selectInquiringBidNodeData(formId);
        // 所属平台名称
        String projectStangeName = StringUtils.isEmpty(headerVO.getFlowForm().getProjectByStage()) ? vo.getExtWFowForm().getProjectName() : headerVO.getFlowForm().getProjectByStage();
        flowForm.addItem("cgsxmc", projectStangeName + "." + headerVO.getFlowForm().getPurchaseItemName() + "-采购方案");
        // 操作人员所属部门
        Users us = getCurrentUser();
        flowForm.addItem("ShenBanBullen", us.getDeptuuid());
        //  事项类型
        flowForm.addItem("ShiXiangLeiXing", "");
        //  情况说明
        flowForm.addItem("QingKuangShuolling", projectStangeName + "." + headerVO.getFlowForm().getPurchaseItemName() + "-采购方案请领导审批！");
        //  附件
        flowForm.addItem("FuJian", "");

        // 发包人
        flowForm.addItem("FBR", headerVO.getFlowForm().getOriginatorUser());
        // 所属小平台
        flowForm.addItem("SSXPT", "");
        // 项目名称
//        flowForm.addItem("XMMC", datas.get());
        // 详细信息链接2
        String detailUrl = StringUtils.replace(purchaseSolutionPageUrl, "{0}", formId) + "?mbs=1";
        flowForm.addItem("XXXXLJ2", cgrBpmTurnUrl + URLEncoder.encode(detailUrl, "UTF-8"));
        CgrBpmTemplateUtil.FlowTemplate flowTemplate = getFlowTemplate(CgrBpmTemplateUtil.FlowKindEnum.purchaseSolution, headerVO.getFlowForm().getProjectId());
        flowForm.setFlowCode(flowTemplate.code);
        System.out.println(JSONObject.toJSON(flowForm));
        LicenseUtil.INSTANCE.validate();
        return flowForm;
    }


    /***
     * 调用招标文件接口
     * @param flowFormDataVo
     * @return
     */
    @Override
    public Map<String, Object> invokeApprovalBidDoc(FlowFormDataVo flowFormDataVo) {
        try {
            LicenseUtil.INSTANCE.validate();
            System.out.println("===========BpmUtil-->invokeApprovalBidDoc");
            CgrFlowForm flowForm = createBidDocFormData(flowFormDataVo);
            Gson gson = new Gson();
            Map<String, Object> mapData = new HashMap<String, Object>();
            mapData.put("data", flowFormDataVo); //数据
            //查询定标流程
            Map<String, Object> q = new HashMap<>();
            q.put("subRelatedId", flowFormDataVo.getSfServiceUuid());
            q.put("bpmRelatedType", "BidDoc");
            String workflowId = sBpmService.getBpmWorkflowId(q);

            Map<String, String> params = new HashMap<String, String>();
//            params.put("workflowCode", this.biddocWorkflowCode);

            params.put("workflowCode", flowForm.getFlowCode());

            Users us = getCurrentUser();
            params.put("userCode", StringUtils.object2StringNotNull(us.getUsername()));
//            params.put("userCode", StringUtils.object2StringNotNull(flowFormDataVo.getScCreateUserName()));
            params.put("finishStart", "true");
            params.put("subTableName", "");
            params.put("RejectInstanceid", StringUtils.object2StringNotNull(workflowId));
            String returnResult = "";
            if ("Y".equals(this.enablePurchaseBpm)) {
                //生产环境
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                returnResult = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_6.getCode());
            } else if ("test".equals(this.enablePurchaseBpm)) {
                //金源测试环境
                params.put("userCode", this.testUsercode);
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                returnResult = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_6.getCode());
            } else {
                //开发环境
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_6.getCode());
            }

            String paramJson = JSON.toJSONString(params);
            logger.info("SynDataServiceImpl[invokeApprovalBidDoc],ParamJson[" + paramJson + "],Result[" + returnResult + "]");

            System.out.println("============doAbutmentBpm=======[result]=========" + returnResult);

            String cgrWorkflowId = "";
            BpmFlowReturn bpmFlowReturn = new BpmFlowReturn();
            if (StringUtils.isNotEmpty(returnResult)) {
                String content = returnResult.substring(returnResult.indexOf("{"), returnResult.indexOf("}") + 1);
                if (StringUtils.isNotEmpty(content)) {
                    CgrFlowReturn cgrFlowReturn = gson.fromJson(content, new TypeToken<CgrFlowReturn>() {
                    }.getType());
                    if (cgrFlowReturn != null) {
                        if ("true".equals(cgrFlowReturn.getSuccess())) {
                            cgrWorkflowId = cgrFlowReturn.getData();
                            bpmFlowReturn.setWorkFlowId(cgrFlowReturn.getData());
                            bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                            bpmFlowReturn.setUrl("");
                            bpmFlowReturn.setFormId("1");
                            saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_BID_DOC.getCode(), flowFormDataVo.getSfServiceUuid(), flowFormDataVo.getSfServiceUuid(), "BidDoc", bpmFlowReturn, returnResult, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                        } else {
                            saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_BID_DOC.getCode(), flowFormDataVo.getSfServiceUuid(), flowFormDataVo.getSfServiceUuid(), "BidDoc", bpmFlowReturn, "", JSON.toJSONString(params), CommonConstants.NO_INTEGER);
                            throw new RuntimeException("流程发起失败！！!");
                        }
                    } else {
                        throw new RuntimeException("流程发起失败！！!");
                    }
                } else {
                    throw new RuntimeException("流程发起失败！！!");
                }
            } else {
                if ("Y".equals(this.enablePurchaseBpm) || "test".equals(this.enablePurchaseBpm)) {
                    throw new RuntimeException("流程发起失败！！!");
                }
                String workFlowId = IdGenUtils.uuid();
                bpmFlowReturn.setWorkFlowId(workFlowId);
                bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                bpmFlowReturn.setUrl("");
                bpmFlowReturn.setFormId("1");
                saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_BID_DOC.getCode(), flowFormDataVo.getSfServiceUuid(), flowFormDataVo.getSfServiceUuid(), "BidDoc", bpmFlowReturn, returnResult, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                //直接审批回调
                if ("autoPass".equals(this.enablePurchaseBpm)) {
                    Map<String, String> callParams = new HashMap<>();
                    callParams.put("evenType", "1");
                    callParams.put("BPMId", workFlowId);
                    this.bpmCallback(callParams);
                } else if ("autoUnPass".equals(this.enablePurchaseBpm)) {
                    Map<String, String> callParams = new HashMap<>();
                    callParams.put("evenType", "2");
                    callParams.put("BPMId", workFlowId);
                    this.bpmCallback(callParams);
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("IS_SUCCESS", true);
            result.put("BPM_URL", this.cgrBpmDetailUrl + cgrWorkflowId);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("流程发起失败", e);
        }
    }

    /**
     * 生成招标文件流程表单
     */
    private CgrFlowForm createBidDocFormData(FlowFormDataVo flowFormDataVo) throws UnsupportedEncodingException {
        LicenseUtil.INSTANCE.validate();
        CgrFlowForm flowForm = new CgrFlowForm();
        String formId = flowFormDataVo.getSfServiceUuid();
        //1、查询采购方案
        HeaderVO headerVO = workFlowService.selectHeaderList(formId);
        PurchasePlanNodeAllDataResVO vo = workFlowService.selectPurchasePlanNodeData(formId);
        SysDict dictContractValuationMethod = sysDictService.getSysDictByValueAndType(headerVO.getFlowForm().getContractValuationMethod() + "", DictTypeConstants.SYS_DICT_TYPE_CONTRACT_VALUATION_METHOD_TYPE_MAP);
        ConfirmBidNodeAllDataResVO datas = workFlowService.selectConfirmBidNodeData(formId);
        InquiringBidRspVO jspp = workFlowService.selectInquiringBidNodeData(formId);
        // 所属平台名称
        flowForm.addItem("titile", headerVO.getFlowForm().getProjectByStage() + "." + headerVO.getFlowForm().getPurchaseItemName() + "-招标文件");
        // 操作人员所属部门
        Users us = getCurrentUser();
        flowForm.addItem("ShenBanBuMen", us.getDeptuuid());
        //  事项类型
        flowForm.addItem("ShiXiangLeiXing", "");
        //  情况说明
        flowForm.addItem("QingKuangShuoMing", headerVO.getFlowForm().getProjectByStage() + "." + headerVO.getFlowForm().getPurchaseItemName() + "-招标文件请领导审批！");
        //  附件
        flowForm.addItem("FuJian", "");

        // 发包人
        flowForm.addItem("FBR", headerVO.getFlowForm().getOriginatorUser());
        // 所属小平台
        flowForm.addItem("SSXPT", "");
        // 项目名称
        flowForm.addItem("XMMC", headerVO.getFlowForm().getProjectScale());
        // 详细信息链接2
        String detailUrl = StringUtils.replace(biddocPageUrl, "{0}", formId) + "?mbs=1";
        flowForm.addItem("XXXXLJ2", cgrBpmTurnUrl + URLEncoder.encode(detailUrl, "UTF-8"));

        CgrBpmTemplateUtil.FlowTemplate flowTemplate = getFlowTemplate(CgrBpmTemplateUtil.FlowKindEnum.purchaseDoc, headerVO.getFlowForm().getProjectId());
        flowForm.setFlowCode(flowTemplate.code);

        System.out.println(JSONObject.toJSON(flowForm));
        return flowForm;
    }

    /***
     * 调用定标接口
     * @param flowFormDataVo
     * @return
     */
    @Override
    public Map<String, Object> invokeApprovalCalibrationBid(FlowFormDataVo flowFormDataVo) {
        LicenseUtil.INSTANCE.validate();
        try {
            System.out.println("===========BpmUtil-->invokeApprovalCalibrationBid");
            CgrFlowForm flowForm = null;
            flowForm = createCalibrationBidFormData(flowFormDataVo);

            Gson gson = new Gson();
            Map<String, Object> q = new HashMap<>();
            q.put("subRelatedId", flowFormDataVo.getSdServiceUuid());
            q.put("bpmRelatedType", "CalibrationBid");
            String workflowId = sBpmService.getBpmWorkflowId(q);

            Users us = getCurrentUser();
            Map<String, String> params = new HashMap<String, String>();
            params.put("workflowCode", flowForm.getFlowCode());
            params.put("userCode", StringUtils.object2StringNotNull(us.getUsername()));
            params.put("finishStart", "true");
            params.put("subTableName", "yongyinneirong3;BJQK;ZBSJ");
            params.put("RejectInstanceid", StringUtils.object2StringNotNull(workflowId));
            String returnResult = "";
            if ("Y".equals(this.enablePurchaseBpm)) {
                //生产环境
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                returnResult = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_7.getCode());
            } else if ("test".equals(this.enablePurchaseBpm)) {
                //金源测试环境
                params.put("userCode", this.testUsercode);
                params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
                returnResult = HttpClientUtils.sendPostRequest(this.cgrBpmUrl, params, null, null);
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_7.getCode());
            } else {
                //开发环境
                saveSynLog("true", flowFormDataVo, CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_7.getCode());
            }

            String paramJson = JSON.toJSONString(params);
            logger.info("SynDataServiceImpl[invokeApprovalCalibrationBid],ParamJson[" + paramJson + "],Result[" + returnResult + "]");

            System.out.println("============invokeApprovalCalibrationBid=======[result]=========" + returnResult);

            String cgrWorkflowId = "";
            BpmFlowReturn bpmFlowReturn = new BpmFlowReturn();
            if (StringUtils.isNotEmpty(returnResult)) {
                String content = returnResult.substring(returnResult.indexOf("{"), returnResult.indexOf("}") + 1);
                if (StringUtils.isNotEmpty(content)) {
                    CgrFlowReturn cgrFlowReturn = gson.fromJson(content, new TypeToken<CgrFlowReturn>() {
                    }.getType());
                    if (cgrFlowReturn != null) {
                        if ("true".equals(cgrFlowReturn.getSuccess())) {
                            cgrWorkflowId = cgrFlowReturn.getData();
                            bpmFlowReturn.setWorkFlowId(cgrFlowReturn.getData());
                            bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                            bpmFlowReturn.setUrl("");
                            bpmFlowReturn.setFormId("1");
                            saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_CALIBRATION_BID.getCode(), flowFormDataVo.getSdServiceUuid(), flowFormDataVo.getSdServiceUuid(), "CalibrationBid", bpmFlowReturn, returnResult, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                        } else {
                            saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_CALIBRATION_BID.getCode(), flowFormDataVo.getSdServiceUuid(), flowFormDataVo.getSdServiceUuid(), "CalibrationBid", bpmFlowReturn, "", JSON.toJSONString(params), CommonConstants.NO_INTEGER);
                            throw new RuntimeException("流程发起失败！！!");
                        }
                    } else {
                        throw new RuntimeException("流程发起失败！！!");
                    }
                } else {
                    throw new RuntimeException("流程发起失败！！!");
                }
            } else {
                if ("Y".equals(this.enablePurchaseBpm) || "test".equals(this.enablePurchaseBpm)) {
                    throw new RuntimeException("流程发起失败！！!");
                }
                String workFlowId = IdGenUtils.uuid();
                bpmFlowReturn.setWorkFlowId(workFlowId);
                bpmFlowReturn.setState(CommonConstants.YES_INTEGER + "");
                bpmFlowReturn.setUrl("");
                bpmFlowReturn.setFormId("1");
                saveSBpm(flowFormDataVo.getScCreateUserName(), AbutmentTypeEnum.PURCHASE.getCode(), AbutmentSubTypeEnum.LINE_STATUS_CALIBRATION_BID.getCode(), flowFormDataVo.getSdServiceUuid(), flowFormDataVo.getSdServiceUuid(), "CalibrationBid", bpmFlowReturn, returnResult, JSON.toJSONString(params), CommonConstants.YES_INTEGER);
                //直接审批回调
                if ("autoPass".equals(this.enablePurchaseBpm)) {
                    Map<String, String> callParams = new HashMap<>();
                    callParams.put("evenType", "1");
                    callParams.put("BPMId", workFlowId);
                    this.bpmCallback(callParams);
                } else if ("autoUnPass".equals(this.enablePurchaseBpm)) {
                    Map<String, String> callParams = new HashMap<>();
                    callParams.put("evenType", "2");
                    callParams.put("BPMId", workFlowId);
                    this.bpmCallback(callParams);
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("IS_SUCCESS", true);
            result.put("BPM_URL", this.cgrBpmDetailUrl + cgrWorkflowId);
            return result;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    private CgrFlowForm createCalibrationBidFormData(FlowFormDataVo flowFormDataVo) throws UnsupportedEncodingException {
        LicenseUtil.INSTANCE.validate();
        CgrFlowForm flowForm = new CgrFlowForm();
        String formId = flowFormDataVo.getSdServiceUuid();
        //查询定标表单所需数据
        //1、查询采购方案
        HeaderVO headerVO = workFlowService.selectHeaderList(formId);
        PurchasePlanNodeAllDataResVO vo = workFlowService.selectPurchasePlanNodeData(formId);
        SysDict dictContractValuationMethod = sysDictService.getSysDictByValueAndType(headerVO.getFlowForm().getContractValuationMethod() + "", DictTypeConstants.SYS_DICT_TYPE_CONTRACT_VALUATION_METHOD_TYPE_MAP);
        ConfirmBidNodeAllDataResVO datas = workFlowService.selectConfirmBidNodeData(formId);
        PSpecialPurchasePlan specialPurchasePlan = pSpecialPurchasePlanService.selectById(headerVO.getFlowForm().getPurchasePlanId());
        // 供方名称
        // 所属平台名称
        flowForm.addItem("title", headerVO.getFlowForm().getProjectByStage() + "." + headerVO.getFlowForm().getPurchaseItemName() + "-定标申请！");
        // 操作人员所属部门
        Users us = getCurrentUser();
        flowForm.addItem("ShenBanBuMen", us.getDeptuuid());
        //  事项类型
        flowForm.addItem("ShiXiangLeiXing", "");
        //  情况说明
        flowForm.addItem("QingKuangShuoMing", headerVO.getFlowForm().getProjectByStage() + "." + headerVO.getFlowForm().getPurchaseItemName() + "-定标请领导审批！");
        //  附件
        flowForm.addItem("FuJian", "");

        // 发包人
        flowForm.addItem("FBR", headerVO.getFlowForm().getOriginatorUser());
        // 所属小平台
        flowForm.addItem("SSXPT", "");
        // 项目位置
        flowForm.addItem("XMWZ", headerVO.getFlowForm().getProjectLocation());
        // 项目规模
        flowForm.addItem("XMGM", headerVO.getFlowForm().getProjectScale());
        // 采购方案地址
        String detailUrl = StringUtils.replace(purchaseSolutionPageUrl, "{0}", flowFormDataVo.getSdServiceUuid()) + "?mbs=1";
        flowForm.addItem("CGFASPLJ", cgrBpmTurnUrl + URLEncoder.encode(detailUrl, "UTF-8"));
        // 采购方式 PurchasePlanFlowTypeEnum
        flowForm.addItem("CGFS", PurchasePlanFlowTypeEnum.getNameByKey(headerVO.getFlowForm().getPurchaseType()));
        // 合约计价方式
        if (!Objects.isNull(dictContractValuationMethod)) {
            flowForm.addItem("HYJJFS", dictContractValuationMethod.getDictDescription());
        }
        // 目标成本（元）
        flowForm.addItem("MBCB", "");
        if (specialPurchasePlan != null && specialPurchasePlan.getPlanBudgetPrices() != null) {
            flowForm.addItem("MBCB", moneyFormat(specialPurchasePlan.getPlanBudgetPrices()));
        }
        // 拟中标金额（元）
//        flowForm.addItem("NZBJE", "");
        // 目标成本建面单方 （元/㎡）
        flowForm.addItem("MBCBJMDF", "");
        // 拟中标金额建面单方 （元/㎡）
        flowForm.addItem("NZBJEJMDF", "");

        // 采购情况简述
        flowForm.addItem("CGQKJS", "");

        // 招标时间节点
        CgrFlowFormItem zbsj = flowForm.addItem("ZBSJ", "", "");
        List<Object> zbsj_ZBItemParamList = new ArrayList<>();
        List<CgrFlowFormItem> zbsjList = new ArrayList<>();
        // 发标时间

        if (!Objects.isNull(vo.getWflowFormTimeNode())) {
            if (!Objects.isNull(vo.getWflowFormTimeNode().getSendBid())) {
                zbsjList.add(CgrFlowForm.createItem("FBSJ", DateUtils.formatDate(vo.getWflowFormTimeNode().getSendBid(), null)));
            }
            // 回标时间
            if (!Objects.isNull(vo.getWflowFormTimeNode().getBackBid())) {
                zbsjList.add(CgrFlowForm.createItem("HBSJ", DateUtils.formatDate(vo.getWflowFormTimeNode().getBackBid(), null)));
            }
            // 商务谈判发起时间
            if (!Objects.isNull(vo.getWflowFormTimeNode().getBusinessNegotiationsLunch())) {
                zbsjList.add(CgrFlowForm.createItem("SWFQSJ", DateUtils.formatDate(vo.getWflowFormTimeNode().getBusinessNegotiationsLunch(), null)));
            }
            // 商务谈判截止时间
            if (!Objects.isNull(vo.getWflowFormTimeNode().getInitBusinessNegoteReturn())) {
                zbsjList.add(CgrFlowForm.createItem("SWJZSJ", DateUtils.formatDate(vo.getWflowFormTimeNode().getInitBusinessNegoteReturn(), null)));
            }
            // 评标完成时间
            if (!Objects.isNull(vo.getWflowFormTimeNode().getInitBidEvaluation())) {
                zbsjList.add(CgrFlowForm.createItem("PBWCSJ", DateUtils.formatDate(vo.getWflowFormTimeNode().getInitBidEvaluation(), null)));
            }
        }

        zbsj_ZBItemParamList.add(zbsjList);
        zbsj.setZBItemParamList(zbsj_ZBItemParamList);

        //拟中标供应商链接
        StringBuilder nzbgyslj = new StringBuilder();
        Double bidAmount = 0.0d;
        List<CalibrationInfoRspVO> inforesp = datas.getCalibrationInfoRspVOS(); //多标段标段
        if (inforesp == null || inforesp.size() == 0) {
            // 拟中标供应商
            flowForm.addItem("NZBGYS", "");
            // 拟中标金额（元）
            flowForm.addItem("NZBJE", "");
        } else {
            // 供应商报价
            CgrFlowFormItem gfbj = flowForm.addItem("BJQK", "", "");
            List<Object> gfbj_ZBItemParamList = new ArrayList<>();
            StringBuilder nzbgys = new StringBuilder();
            StringBuilder nzbje = new StringBuilder();

            for (CalibrationInfoRspVO bd : inforesp) {
                List<ExtWFlowFormBackBid> backbids = bd.getFlowFormBackBids();
                StringBuilder sb = new StringBuilder();
                StringBuilder zbje = new StringBuilder();
                sb.append("标段").append(bd.getSegmentsNumber()).append("：");
                zbje.append("标段").append(bd.getSegmentsNumber()).append("：");
                for (ExtWFlowFormBackBid backBid : backbids) {
                    List<CgrFlowFormItem> list = new ArrayList<>();
                    // 标段
                    list.add(CgrFlowForm.createItem("BDH", backBid.getSegmentsNumber() + ""));
                    // 单位名称
                    list.add(CgrFlowForm.createItem("DWMC", "(标段" + bd.getSegmentsNumber() + ")" + backBid.getSupplierName()));
                    // 首轮报价
                    list.add(CgrFlowForm.createItem("SLBJ", moneyFormat(backBid.getRoundOneWithTax())));
                    // 二轮报价
                    list.add(CgrFlowForm.createItem("ELBJ", moneyFormat(backBid.getBusinessNegotiationWithTax())));
                    // 最终报价
                    list.add(CgrFlowForm.createItem("ZZBJ", moneyFormat(this.getAwardBidAmount(backBid))));

                    // 最终报价建面单方
                    list.add(CgrFlowForm.createItem("ZZBJDF", ""));
                    // 商务标排名
                    list.add(CgrFlowForm.createItem("SWBPM", ""));
                    // 技术标情况
                    list.add(CgrFlowForm.createItem("JSBQK", Objects.isNull(backBid.getTechnicalScore()) ? "" : backBid.getTechnicalScore() + ""));
                    // 是否中标
                    list.add(CgrFlowForm.createItem("SFZB", backBid.getAwardBidOrNot() == 1 ? "是" : "否"));

                    if (backBid.getAwardBidOrNot() == 1) {
                        String supplierUrl = awardbidSupplierUrl + backBid.getSupplierId() + "&mbs=1";
                        String ssoSupplierUrl = cgrBpmTurnUrl + URLEncoder.encode(supplierUrl, "UTF-8");
                        //详情地址
                        nzbgyslj.append(String.format("<a href='%s' target='view_window'>%s</a>&nbsp;&nbsp;", ssoSupplierUrl, backBid.getSupplierName()));

                    }

                    if (backBid.getAwardBidOrNot() == 1) {
                        sb.append(backBid.getSupplierName()).append(",");
                        Double b = this.getAwardBidAmount(backBid);
                        if (b != null) {
                            zbje.append(moneyFormat(b)).append("（元）,");
                            bidAmount += b;
                        }
                    }
                    gfbj_ZBItemParamList.add(list);
                }
                nzbgys.append(sb.substring(0, sb.length() - 1)).append("; ");
                nzbje.append(zbje.substring(0, zbje.length() - 1)).append("; ");
            }
            flowForm.addItem("NZBGYS", nzbgys.substring(0, nzbgys.length() - 1));
            flowForm.addItem("NZBJE", nzbje.substring(0, nzbje.length() - 1));
            gfbj.setZBItemParamList(gfbj_ZBItemParamList);
        }

        if(bidAmount > specialPurchasePlan.getPlanBudgetPrices()){
            throw new RuntimeException(String.format("中标金额大于了标底金额:%s>%s",bidAmount,specialPurchasePlan.getPlanBudgetPrices()));
        }

        // 定标建议
        flowForm.addItem("DBJY", headerVO.getFlowForm().getCalibrationConclusion());
        // 付款方式描述
        flowForm.addItem("FKFS", headerVO.getFlowForm().getPaymentType());

        //中标单位详情地址
        flowForm.addItem("NZBGYSLJ", nzbgyslj.toString());


        // 用印
        CgrFlowFormItem yy = flowForm.addItem("yongyinneirong3", "", "");
        List<Object> yy_ZBItemParamList = new ArrayList<>();
        List<CgrFlowFormItem> yyItemList = new ArrayList<>();
        // 印章公司
        yyItemList.add(CgrFlowForm.createItem("YZGS", ""));
        // 印章类型
        yyItemList.add(CgrFlowForm.createItem("YZLX", ""));
        // 用印材料名称
        yyItemList.add(CgrFlowForm.createItem("YYCLMC", ""));
        // 份数
        yyItemList.add(CgrFlowForm.createItem("fs", ""));
        // 外带
        yyItemList.add(CgrFlowForm.createItem("wd", ""));
        // 外带开始日期
        yyItemList.add(CgrFlowForm.createItem("wdksrq", ""));
        // 外带结束日期
        yyItemList.add(CgrFlowForm.createItem("wdjsrq", ""));
        yy_ZBItemParamList.add(yyItemList);
        yy.setZBItemParamList(yy_ZBItemParamList);

        // 招标小组成员
        StringBuilder jsz = new StringBuilder("");
        StringBuilder swz = new StringBuilder("");
        for (WFlowFormPurchaseTeam team : vo.getWflowFormPurchaseTeams()) {
            if (team.getPurchaseJob() == 3 || team.getPurchaseJob() == 4) {
                //技术组
                jsz.append(team.getUserId()).append(",");
            } else if (team.getPurchaseJob() == 2 || team.getPurchaseJob() == 1) {
                //经济组
                swz.append(team.getUserId()).append(",");
            }
        }
        if ("test".equals(this.enablePurchaseBpm)) {
            // 技术组成员
            flowForm.addItem("jszcy", "louqun,lipeng");
            // 商务组成员
            flowForm.addItem("swzcy", "zukecs1,100070");
        } else {
            // 技术组成员
            if (jsz != null && jsz.length() > 0) {
                flowForm.addItem("jszcy", jsz.substring(0, jsz.length() - 1));
            }
            // 商务组成员
            if (swz != null && swz.length() > 0) {
                flowForm.addItem("swzcy", swz.substring(0, swz.length() - 1));
            }
        }

        // 印章管理员
        flowForm.addItem("YZGUL", "");
        // 所属小平台
        flowForm.addItem("SSXPT1", "");
        // 详细信息链接2
        String detailUrl2 = StringUtils.replace(calibrationBidPageUrl, "{0}", formId) + "?mbs=1";
        flowForm.addItem("XXXXLJ2", cgrBpmTurnUrl + URLEncoder.encode(detailUrl2, "UTF-8"));


        CgrBpmTemplateUtil.FlowTemplate flowTemplate = getFlowTemplate(CgrBpmTemplateUtil.FlowKindEnum.purchaseCalibrationBid, headerVO.getFlowForm().getProjectId());
        flowForm.setFlowCode(flowTemplate.code);

        System.out.println(JSONObject.toJSON(flowForm));
        return flowForm;
    }

    public Double getAwardBidAmount(ExtWFlowFormBackBid backBid) {
        LicenseUtil.INSTANCE.validate();
        if (backBid == null) {
            return 0d;
        }
        //定标约谈
        if (backBid.getCalibrationFinalTax() != null) {
            return backBid.getCalibrationFinalTax();
        }
        //评标约谈
        if (backBid.getFinalInterviewWithTax() != null) {
            return backBid.getFinalInterviewWithTax();
        }
        //商务谈判
        if (backBid.getBusinessNegotiationWithTax() != null) {
            return backBid.getBusinessNegotiationWithTax();
        }
        //二轮回村
        if (backBid.getRoundTwoWithTax() != null) {
            return backBid.getRoundTwoWithTax();
        }
        //一轮回村
        if (backBid.getRoundOneWithTax() != null) {
            return backBid.getRoundOneWithTax();
        }
        return 0d;
    }

    public void saveSynLog(String result, FlowFormDataVo flowFormDataVo, Integer type) {
        LicenseUtil.INSTANCE.validate();
        if (flowFormDataVo != null && "true".equalsIgnoreCase(result)) {
            String uuid = "";
            if (CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_5.getCode() == type) {
                uuid = flowFormDataVo.getScServiceUuid();
            } else if (CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_6.getCode() == type) {
                uuid = flowFormDataVo.getSfServiceUuid();
            } else if (CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_7.getCode() == type) {
                uuid = flowFormDataVo.getSdServiceUuid();
            }
            sAbutmentLogsService.saveAbutmentLogs(type, uuid, JSONArray.toJSONString(flowFormDataVo), 1, 1);
        } else {
            throw new RuntimeException("对接失败");
        }
    }

    /***
     * 保存bpm对接数据
     * @param currentUserId
     * @param abutmentType
     * @param abutmentSubType
     * @param relatedId
     * @param subRelatedId
     * @param bpmRelatedType
     * @param bpmFlowReturn
     * @param abutmentResult
     */
    private void saveSBpm(String currentUserId, int abutmentType, int abutmentSubType, String relatedId, String subRelatedId, String bpmRelatedType, BpmFlowReturn bpmFlowReturn, String abutmentResult, String paramJson, Integer currentBpmFlag) {
        SBpm sBpm = new SBpm();
        sBpm.setId(IdGenUtils.uuid());
        sBpm.setAbutmentType(abutmentType);
        sBpm.setAbutmentSubType(abutmentSubType);
        sBpm.setRelatedId(relatedId);
        sBpm.setSubRelatedId(subRelatedId);
        sBpm.setBpmRelatedType(bpmRelatedType);
        sBpm.setFormId(bpmFlowReturn.getFormId() + "");
        sBpm.setWorkFlowId(bpmFlowReturn.getWorkFlowId() + "");
        sBpm.setAbutmentPush(paramJson);
        sBpm.setAbutmentStatus(NumberUtils.toInteger(bpmFlowReturn.getState()));
        sBpm.setAbutmentResult(abutmentResult);
        sBpm.setBaseFeilds(currentUserId, "", CommonConstants.NO_INTEGER, true);
        sBpm.setCurrentBpmFlag(currentBpmFlag);
        sBpmService.insert(sBpm);
    }

    /**
     * 流程审批回调
     */
    private void bpmCallback(Map<String, String> requestBody) {
        LicenseUtil.INSTANCE.validate();
        CommonConstants.cachedThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    SBpmCallback sBpmCallback = mbsBpmCallBackService.saveBpmCallBack(requestBody);
                    boolean isSuccess = mbsBpmCallBackService.mbsBpmCallBack(requestBody);
                    SBpmCallback updateCallback = new SBpmCallback();
                    updateCallback.setId(sBpmCallback.getId());
                    updateCallback.setDelFlag(1);
                    mbsBpmCallBackService.updateBpmCallBack(updateCallback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    public static Map<String, Object> map(String key, Object value) {
        Map<String, Object> map = new HashMap<>();
        map.put(key, value);
        return map;
    }

    public static Map<String, String> createTestData() {
        LicenseUtil.INSTANCE.validate();
        // 构建流程对象
        CgrFlowForm flowForm = new CgrFlowForm();
        // 供方名称
        flowForm.addItem("SUPPLIER_NAME", "杭州立方控股股份有限公司");
        // 所属平台名称
        flowForm.addItem("title", "杭州立方控股股份有限公司入库流程审批");
        // 所属平台编号
        flowForm.addItem("ShenBanBuMen", "1");
        flowForm.addItem("ShiXiangLeiXing", "A");
        flowForm.addItem("QingKuangShuoMing", "情况说明 ");
        flowForm.addItem("FuJian", "");
        flowForm.addItem("ShenPiYiJian", "");
        flowForm.addItem("OUCompany", "");

        // 所在区域
        flowForm.addItem("SuoZaiQuyu", "北京");

        // 供方服务类别
        flowForm.addItem("GFFWLB", "工程施工类");

        // 供方类型
        flowForm.addItem("GFLX", "弱电安防智能化工程");

        // 意向平台公司
        flowForm.addItem("YXPTGS", "腾云筑科平台");

        // 可承接省份
        flowForm.addItem("KCJSF", "北京,天津,上海,重庆,河北,山西,辽宁,吉林,黑龙江,江苏,浙江,安徽,福建,江西,山东,河南,湖南,湖北,广东,甘肃,四川,贵州,海南,云南,青海,陕西,广西,西藏,宁夏,新疆,内蒙");

        // 资质等级
        flowForm.addItem("ZZDJ", "无");

        // 上年营业额（万元）
        flowForm.addItem("SNYYE", "35800");

        //供应商来源
        flowForm.addItem("GYSLY", "网络注册");

        // 战略合作情况 子表
        if (true) {
            CgrFlowFormItem zlhzqk = flowForm.addItem("ZLHZQK", "");
            List<Object> zlhzqk_ZBItemParamList = new ArrayList<>();
            for (int i = 0; i < 1; i++) {
                List<CgrFlowFormItem> item = new ArrayList<>();
                item.add(CgrFlowForm.createItem("HZDW", "华润"));
                item.add(CgrFlowForm.createItem("HZLB", "战略集采"));
                item.add(CgrFlowForm.createItem("HZKSSJ", "2016-04-01"));
                item.add(CgrFlowForm.createItem("HZJSSJ", "2021-04-01"));
                item.add(CgrFlowForm.createItem("SHJX", ""));
                item.add(CgrFlowForm.createItem("HZQY", "全国"));
                item.add(CgrFlowForm.createItem("HTJE", "2000"));
                zlhzqk_ZBItemParamList.add(item);
            }
            zlhzqk.setZBItemParamList(zlhzqk_ZBItemParamList);
        }

        if (true) {
            // 一般合作情况 子表
            CgrFlowFormItem ybhzqk = flowForm.addItem("YBHZQK", "");
            List<Object> ybhzqk_ZBItemParamList = new ArrayList<>();
            for (int i = 0; i < 1; i++) {
                List<CgrFlowFormItem> item = new ArrayList<>();
                item.add(CgrFlowForm.createItem("HZDW", "中海地产"));
                item.add(CgrFlowForm.createItem("HZXM", "战略"));
                item.add(CgrFlowForm.createItem("HZKSSJ", "2018-12-31"));
                item.add(CgrFlowForm.createItem("HZJSSJ", "2018-12-31"));
                item.add(CgrFlowForm.createItem("XMGM", "大型"));
                item.add(CgrFlowForm.createItem("HZFW", "停车场、门禁"));
                item.add(CgrFlowForm.createItem("HTJE", "500"));
                ybhzqk_ZBItemParamList.add(item);
            }
            ybhzqk.setZBItemParamList(ybhzqk_ZBItemParamList);
        }


        Map<String, String> params = new HashMap<>();
        params.put("userCode", "zukecs1");
        params.put("workflowCode", "GongFangChuRuKu");
        params.put("finishStart", "true");
        params.put("subTableName", "YBHZQK;ZLHZQK");
        params.put("RejectInstanceid", "");
        params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));
        return params;
    }

    ///
    public static void main(String[] args) {
       /* // 构建流程对象
        CgrFlowForm flowForm = new CgrFlowForm();
        // 供方名称
        flowForm.addItem("SUPPLIER_NAME", "贵州智博优创广告有限公司");
        // 所属平台名称
        flowForm.addItem("title", "贵州智博优创广告有限公司入库流程审批");
        // 所属平台编号
        flowForm.addItem("ShenBanBuMen", "100018");
        flowForm.addItem("ShiXiangLeiXing", "A");
        flowForm.addItem("QingKuangShuoMing", "情况说明 ");
        flowForm.addItem("FuJian", "");
        flowForm.addItem("ShenPiYiJian", "");
        flowForm.addItem("OUCompany", "");

        // 所在区域
        flowForm.addItem("SuoZaiQuyu", "北京");

        // 供方服务类别
        flowForm.addItem("GFFWLB", "工程施工类");

        // 供方类型
        flowForm.addItem("GFLX", "弱电安防智能化工程");

        // 意向平台公司
        flowForm.addItem("YXPTGS", "腾云筑科平台");

        // 可承接省份
        flowForm.addItem("KCJSF", "北京,天津,上海,重庆,河北,山西,辽宁,吉林,黑龙江,江苏,浙江,安徽,福建,江西,山东,河南,湖南,湖北,广东,甘肃,四川,贵州,海南,云南,青海,陕西,广西,西藏,宁夏,新疆,内蒙");

        // 资质等级
        flowForm.addItem("ZZDJ", "无");

        // 上年营业额（万元）
        flowForm.addItem("SNYYE", "35800");

        //供应商来源
        flowForm.addItem("GYSLY", "网络注册");

        // 战略合作情况 子表
        if (true) {
            CgrFlowFormItem zlhzqk = flowForm.addItem("ZLHZQK", "");
            List<Object> zlhzqk_ZBItemParamList = new ArrayList<>();
            for (int i = 0; i < 1; i++) {
                List<CgrFlowFormItem> item = new ArrayList<>();
                item.add(CgrFlowForm.createItem("HZDW", "华润"));
                item.add(CgrFlowForm.createItem("HZLB", "战略集采"));
                item.add(CgrFlowForm.createItem("HZKSSJ", "2016-04-01"));
                item.add(CgrFlowForm.createItem("HZJSSJ", "2021-04-01"));
                item.add(CgrFlowForm.createItem("SHJX", ""));
                item.add(CgrFlowForm.createItem("HZQY", "全国"));
                item.add(CgrFlowForm.createItem("HTJE", "2000"));
                zlhzqk_ZBItemParamList.add(item);
            }
            zlhzqk.setZBItemParamList(zlhzqk_ZBItemParamList);
        }

        if (true) {
            // 一般合作情况 子表
            CgrFlowFormItem ybhzqk = flowForm.addItem("YBHZQK", "");
            List<Object> ybhzqk_ZBItemParamList = new ArrayList<>();
            for (int i = 0; i < 1; i++) {
                List<CgrFlowFormItem> item = new ArrayList<>();
                item.add(CgrFlowForm.createItem("HZDW", "中海地产"));
                item.add(CgrFlowForm.createItem("HZXM", "战略"));
                item.add(CgrFlowForm.createItem("HZKSSJ", "2018-12-31"));
                item.add(CgrFlowForm.createItem("HZJSSJ", "2018-12-31"));
                item.add(CgrFlowForm.createItem("XMGM", "大型"));
                item.add(CgrFlowForm.createItem("HZFW", "停车场、门禁"));
                item.add(CgrFlowForm.createItem("HTJE", "500"));
                ybhzqk_ZBItemParamList.add(item);
            }
            ybhzqk.setZBItemParamList(ybhzqk_ZBItemParamList);
        }


        StartCgrFlowRequestBody startCgrFlowRequestBody = new StartCgrFlowRequestBody();
        // 是否结束第一个活动,传固定值true
        startCgrFlowRequestBody.setFinishStart(true);
        // 流程模板
        startCgrFlowRequestBody.setWorkflowCode("GongFangChuRuKu");
        // 人员ID
        startCgrFlowRequestBody.setUserCode("huangzhen");
        // 表单参数
        System.out.println(JSON.toJSONString(startCgrFlowRequestBody));

        Map<String, String> params = new HashMap<>();
        params.put("userCode", "zukecs1");
        params.put("workflowCode", "GongFangChuRuKu");
        params.put("finishStart", "true");

        params.put("subTableName", "ZLHZQK;YBHZQK");
        params.put("RejectInstanceid", "4fbe6f6b-04b3-43bc-a310-25dfaeb59224");
        params.put("jsonString", JSON.toJSONString(flowForm.getFlowForm()));

        System.out.println(JSON.toJSONString(params));

        String result = HttpClientUtils.sendPostRequest("http://por.test.cgr.com.cn:8010/portal/Webservices/BPMTest2Service.asmx/StartWorkflowNew", params, null, null);
        String content = result.substring(result.indexOf("{"), result.indexOf("}") + 1);
        Gson gson = new Gson();
        CgrFlowReturn bpmFlowReturn = gson.fromJson(content, new TypeToken<CgrFlowReturn>() {
        }.getType());
        System.out.println(bpmFlowReturn);
        System.out.println(result);*/
        System.out.println(moneyFormat(0d));
    }

    private static String moneyFormat(Double money) {
        if (money == null) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("#.##");
        //指定RoundingMode
        df.setRoundingMode(RoundingMode.HALF_UP);
        return df.format(money);
    }


}
